using Digitalmes.Domain.Entities.Mes.Qualities;

namespace Digitalmes.Application.Mes.Qulities.Defects.Queries;

/// <summary>
/// 缺陷定义分页查询命令。
/// </summary>
public sealed record GetDefectListWithPagedQuery(
    string? DefectCode,
    string? DefectName,
    string? DefectType,
    int PageNumber,
    int PageSize) : IPagedQuery, IRequest<IResult<PagedList<QcDefectDefineDto>>>;

internal sealed class GetDefectListWithPagedQueryHandler(IRepository<QcDefectDefine> repo) : IRequestHandler<GetDefectListWithPagedQuery, IResult<PagedList<QcDefectDefineDto>>>
{
    public async Task<IResult<PagedList<QcDefectDefineDto>>> Handle(GetDefectListWithPagedQuery request, CancellationToken cancellationToken)
    {
        var items = await repo.AsQueryable()
            .WhereIF(!string.IsNullOrEmpty(request.DefectCode), m => m.DefectCode == request.DefectCode)
            .WhereIF(!string.IsNullOrEmpty(request.DefectName), m => m.DefectName.Contains(request.DefectName!))
            .WhereIF(!string.IsNullOrEmpty(request.DefectType), m => m.DefectType == request.DefectType)
            .OrderBy(m => new { m.DefectType, m.Order })
            .GetPagedListAsync(request.PageNumber, request.PageSize, cancellationToken);
        return Result.From(items.Adapt<PagedList<QcDefectDefineDto>>());
    }
}
